import os
import uuid
from compile.Answer import Answer
from compile.Question import Question
from compile.CommandUtil import run
from utils.fileUtil import write_file, read_file


class Task:
    def __init__(self):
        self.WORK_DIR = f"./tmp/{uuid.uuid4()}/"
        self.CLASS = "Solution"
        self.CODE = os.path.join(self.WORK_DIR, "Solution.java")
        self.COMPILE_ERROR = os.path.join(self.WORK_DIR, "compileError.txt")
        self.STDOUT = os.path.join(self.WORK_DIR, "stdout.txt")
        self.STDERR = os.path.join(self.WORK_DIR, "stderr.txt")

    def compile_and_run(self, question):
        answer = Answer()

        # 创建工作目录
        os.makedirs(self.WORK_DIR, exist_ok=True)

        # 写入代码到文件
        write_file(self.CODE, question.code)

        # 编译
        compile_cmd = f"javac -encoding utf8 {self.CODE} -d {self.WORK_DIR}"
        run(compile_cmd, None, self.COMPILE_ERROR)
        compile_error = read_file(self.COMPILE_ERROR)

        if compile_error:
            answer.error = 1
            answer.reason = compile_error
            return answer

        # 运行
        run_cmd = f"java -classpath {self.WORK_DIR} {self.CLASS}"
        run(run_cmd, self.STDOUT, self.STDERR)
        run_error = read_file(self.STDERR)
        run_out = read_file(self.STDOUT)

        if run_error:
            answer.error = 2
            answer.reason = run_error
            return answer

        answer.error = 0
        answer.stdout = run_out
        return answer
